package com.syni.mdd.yhd.common.all.aop;

import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.service.BmsCommonService;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.WebUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Order(1)
@Component
@Profile({"pro","dev","preo"})
public class ApiSecurityInterceptor {
    @Autowired
    RedisTemplate redisTemplate;

    private final static String apiKey = "apiMiDongDong0630@";

	private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	BmsCommonService bmsCommonService;

	//@Pointcut("execution(public *  com.syni.mdd.yhd.common.all.controller.TestController.testApiAuth(..))") // 两个..代表所有子目录，最后括号里的两个..代表所有参数
	@Pointcut("execution(public *  com.syni.mdd.yhd.common.all.controller.protect..*.*(..))")
	public void logPointCut() {
	}


	@SuppressWarnings("unchecked")
	@Around("logPointCut()")
	public Object Interceptor(ProceedingJoinPoint pjp) throws Throwable {
		String API_AUTH = bmsCommonService.getAPI_AUTH();
		RequestHeaderData requestHeader = new RequestHeaderData();
		//System.out.println(requestHeader);
		String t  = requestHeader.getString("t");
		String randomStr  = requestHeader.getString("rs");
		String sign = requestHeader.getString("sign");
		String spe = requestHeader.getString("superpermissions");
		if(spe.equals("superpermissions") || API_AUTH.equals(Constants.COMMON_FLAG_FALSE)){
			return pjp.proceed();
		}
		/*if(StringUtils.isNotBlank(t) && StringUtils.isNotBlank(randomStr)
				&& StringUtils.isNotBlank(sign)) {*/
			//String admin = requestHeader.getString("admin");
			//if (!"admin".equals(admin)) {
			if (!(StringUtils.isNotBlank(t) && StringUtils.isNotBlank(randomStr)
					&& StringUtils.isNotBlank(sign))) {
				log.info("请求无效原因：丢失参数...........");
				return ResultMapHelper.result(ResultCode.CODE_ERROR_111,ResultMsg.REQUEST_FAIL);
			}
			Integer timestamp = Integer.parseInt(t, 16);
			System.out.println("请求时间戳：" + timestamp);
			int nowTime = (int) (System.currentTimeMillis() / 1000);
			if (nowTime - timestamp > 300) {
				log.info("请求无效原因：5分钟之前的请求");
				return ResultMapHelper.result(ResultCode.CODE_ERROR_111,ResultMsg.REQUEST_FAIL);
			}
			String URI = requestHeader.getHttpServletRequest().getRequestURI();
			log.info("URI : " + URI);
			String serverSign = WebUtils.MD5(apiKey + URI + t + randomStr).toLowerCase();
			if (!serverSign.equals(sign)) {
				log.info("请求无效原因：第一次sign匹配失败");
				log.info("serverSign : " + serverSign);
				//兼容转发过来的路径
				URI = "/MDD_API" + URI;
				serverSign = WebUtils.MD5(apiKey + URI + t + randomStr).toLowerCase();
				if(!serverSign.equals(sign)) {
					log.info("请求无效原因：sign匹配失败");
					log.info("rs : " + randomStr);
					log.info("sign : " + sign);
					log.info("t : " + t);
					log.info(" -----------------------------------------");
					log.info("serverSign : " + serverSign);
					return ResultMapHelper.result(ResultCode.CODE_ERROR_111,ResultMsg.REQUEST_FAIL);
				}
			}
			if (!redisTemplate.opsForValue().setIfAbsent(Constants.REDIS_KEY_API_INTECEPTOR + sign, 1, 5, TimeUnit.MINUTES)) {
				log.info("请求无效原因：sign已被使用");
				return ResultMapHelper.result(ResultCode.CODE_ERROR_111,ResultMsg.REQUEST_FAIL);
			}
			log.info("t : " + t);
			log.info("rs : " + randomStr);
			log.info("sign : " + sign);
		//}
		return pjp.proceed();
	}
}
